//
//  WBStatusPictureView.swift
//  ZWWEIBO
//
//  Created by xzw on 2018/4/10.
//  Copyright © 2018年 xzw. All rights reserved.
//

import UIKit

class WBStatusPictureView: UIView {

    var viewModel : WBStatusViewModel? {
        didSet {
            calcViewSize()
        }
    }
    // 根据视图模型的配图视图大小，调整显示内容
    private func calcViewSize(){
        //处理宽度
        //1.单图，根据配图视图的大小，修改subview[0]的宽高
        if viewModel?.picURLs?.count == 1 {
            let viewSize = viewModel?.pictureViewSize ?? CGSize()
            let view = subviews[0]
            view.frame = CGRect(x: 0, y: WBPicViewOutMargin, width: viewSize.width, height: viewSize.height)
        }else
        {
             //2.多图，恢复subview[0]的宽高，保证九宫格布局
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: WBPicViewOutMargin, width: WBPictureItemW, height:WBPictureItemW )
            
        }
        
        
        //修改高度约束
        heightCons.constant = viewModel?.pictureViewSize.height ?? 0
    }
    
    //配图视图模型
    var urls : [WBStatusPicture]? {
        didSet{
            
            //1.隐藏所有imageView
            for v in subviews {
                v.isHidden = true
            }
            
            //2.遍历数组，顺序设置图片
            var index = 0
            for url in urls ?? [] {
               
                let iv = subviews[index] as! UIImageView
                
                //当只有四张图片的时候
                if index == 1 && urls?.count == 4{
                    index += 1 //跳过一张
                }
                
                iv.zw_setImage(urlStr: url.thumbnail_pic, placeholderImage: nil)
                iv.isHidden = false
                
                index += 1
            }
        }
    }
    
    @IBOutlet weak var heightCons: NSLayoutConstraint!
  
    override func awakeFromNib() {
        super.awakeFromNib()
        
        clipsToBounds = true //裁掉超过父视图的部分
        setupUI()
    }
    
}

 //MARK: -  设置界面
extension WBStatusPictureView {
    
    //1.cell中所有的控件都是提前准备好
    //2.设置的时候，根据数据决定是否显示
    //3.不要动态创建控件
    
    private func setupUI() {
        
        backgroundColor = superview?.backgroundColor //设置成跟父视图一样的背景颜色
        
        let count = 3
        let rect = CGRect(x: 0, y: WBPicViewOutMargin, width: WBPictureItemW, height: WBPictureItemW)
        
        for i in 0..<count*count {
            let iv = UIImageView()
            
            iv.backgroundColor = UIColor.white
            
            //行 -> y
            let row = CGFloat(i / count)
            
            //列 -> x
            let col = CGFloat(i % count)
            
            let xOffset = col * (WBPictureItemW + WBPicViwInnerMargin)
            let yOffset = row * (WBPictureItemW + WBPicViwInnerMargin)
                
            iv.frame = rect.offsetBy(dx: xOffset, dy: yOffset)
                
                
            addSubview(iv)
        }
    }
}
